<template>
  <div class="page-wapper">
    <!-- 日报汇总 -->
    <el-row :gutter="20" style="flex: 1; overflow: hidden">
      <el-col :span="5" style="height: 100%">
        <el-card
          shadow="hover"
          :body-style="{
            flex: 1,
            padding: 0,
            'box-sizing': 'border-box',
            overflow: 'hidden',
          }"
          style="height: 100%; display: flex; flex-direction: column"
        >
          <template #header>
            <div class="clearfix">
              <span>组织人员</span>
            </div>
          </template>
          <div class="person_list">
            <div class="person_content">
              <div v-for="(item, i) in pageData" :key="i" class="cell_box">
                <div
                  :style="{
                    background: i % 2 == 0 ? '#C0C4CC' : '#C0C4CC',
                  }"
                  class="group_box"
                >
                  <span v-for="(cell, j) in item.groupName.split('')" :key="j">
                    {{ cell }}
                  </span>
                </div>
                <div class="person_box">
                  <div
                    v-for="(cell, j) in item.userReportCommitList"
                    :key="j"
                    class="person_item"
                  >
                    <UserAvatar
                      :src="cell.avatar"
                      :showHuangguan="cell.isLeader"
                      :size="50"
                    />
                    <div class="info_name">
                      {{ cell.truename || cell.nickname }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="19" style="height: 100%">
        <el-card
          shadow="hover"
          :body-style="{
            flex: 1,
            padding: 0,
            'box-sizing': 'border-box',
            overflow: 'hidden',
          }"
          style="height: 100%; display: flex; flex-direction: column"
        >
          <template #header>
            <div class="clearfix d_f j_s a_c">
              <div>
                <span>日报汇总：</span>
                <el-date-picker
                  v-model="filterData.createdTime"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="选择日期"
                  size="mini"
                ></el-date-picker>
                <div
                  v-if="$isSupperAdmin()"
                  class="ml_l"
                  style="display: inline-flex"
                >
                  <div>所属机构：</div>
                  <OrgSelect v-model:modelValue="orgInfo" size="mini" />
                </div>
              </div>
              <el-button-group>
                <!-- <el-button size="mini" @click="toggleEditReport">
                  <arrow-left v-if="isShowReportEdit" class="arrow_icon" />
                  <arrow-right v-else class="arrow_icon" />
                </el-button> -->
                <el-button
                  size="mini"
                  :loading="searchBtnLoading"
                  type="primary"
                  @click="handleSearch"
                >
                  查询
                </el-button>
                <el-button size="mini" @click="handleReset"> 重置 </el-button>
              </el-button-group>
            </div>
          </template>
          <div class="swiper_container">
            <div
              :style="{
                transform: `translateX(${isShowReportEdit ? '-50%' : 0})`,
              }"
              class="swiper_content"
            >
              <div class="swiper_slide">
                <div class="report_list">
                  <div class="report_list_content">
                    <div
                      v-for="(row, k) in pageRightData"
                      :key="k"
                      class="report_cell_box"
                    >
                      <div class="report_cell_title">
                        <span>{{ row.truename || row.nickname }}</span>
                        <div v-if="userInfo.isLeader">
                          <el-button
                            v-if="
                              !row.reportCommitList[0] && row.id !== userInfo.id
                            "
                            type="warning"
                            size="mini"
                            plain
                            @click="sendReportNotice(row)"
                            :disabled="
                              row.sendLoadingCount !== INIT_SEND_LOADING_COUNT
                            "
                          >
                            {{
                              row.sendLoadingCount !== INIT_SEND_LOADING_COUNT
                                ? `发送提醒 ${row.sendLoadingCount + 1}s`
                                : "发送提醒"
                            }}
                          </el-button>
                        </div>
                      </div>
                      <div
                        v-if="row.reportCommitList[0]"
                        class="expand_wrapper"
                      >
                        <ReportCommitList
                          :lastFinishReportList="
                            row.reportCommitList[0].lastFinishReportList
                          "
                          :todayPlanReportList="
                            row.reportCommitList[0].todayPlanReportList
                          "
                          :reportCommitRemark="
                            row.reportCommitList[0].reportCommitRemark
                          "
                          titleBg="#f2f6fc"
                        />
                      </div>
                      <div v-else style="color: #999; padding: 10px 20px">
                        <span class="mr_m">今日还未提交</span>
                        <!-- <el-button
                          v-if="!row.isLeader && row.id === userInfo.id"
                          type="danger"
                          size="mini"
                          @click="toggleEditReport"
                        >
                          编辑提交日报
                        </el-button> -->
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="swiper_slide">2</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  reactive,
  ref,
  computed,
  getCurrentInstance,
  onMounted,
  onBeforeUnmount,
  onUnmounted,
} from "vue";
import { ElMessage } from "element-plus";
import { useStore } from "vuex";
import { useRoute } from "vue-router";
import { cloneDeep } from "lodash";
import UserAvatar from "../../components/UserAvatar.vue";
import bus from "../../utils/bus";
import ReportCommitList from "./components/ReportCommitList.vue";
import OrgSelect from "../../components/OrgSelect.vue";

// 发送日报提醒时间间隔（秒）
const INIT_SEND_LOADING_COUNT = 10;

const initFilterData = () => {
  return {
    createdTime: null,
  };
};

export default {
  name: "TodayReportManage",
  components: {
    UserAvatar,
    ReportCommitList,
    OrgSelect,
  },
  setup() {
    const { proxy } = getCurrentInstance();
    const $moment = proxy.$moment;
    const $api = proxy.$api;
    const $route = useRoute();
    const store = useStore();

    // 机构选择组件绑定的数据
    const orgInfo = ref({
      orgId: null,
      orgName: null,
    });

    // 搜索绑定的数据
    const filterData = reactive(initFilterData());
    filterData.createdTime = $moment().format("YYYY-MM-DD");
    // 真正的搜索条件
    const condition = reactive({});
    const searchBtnLoading = ref(false);
    const pageLoading = ref(false);
    const pageData = ref([]);
    const pageRightData = ref([]);

    const userInfo = computed(() => store.state.user.userInfo);

    // 搜索
    const handleSearch = () => {
      Object.keys(filterData).forEach((key) => {
        // 解决后端枚举类型传空字符串解析报错的问题
        condition[key] = filterData[key] === "" ? null : filterData[key];
      });
      // 处理机构搜索参数
      condition.orgId = orgInfo.value.orgId;
      getPageData();
    };

    // 获取列表数据
    const getPageData = () => {
      pageLoading.value = true;
      const params = {
        startCreatedTime: condition.createdTime
          ? condition.createdTime + " 00:00:00"
          : null,
        endCreatedTime: condition.createdTime
          ? condition.createdTime + " 23:59:59"
          : null,
        orgId: condition.orgId,
      };
      if (!params.orgId) {
        pageData.value = [];
        pageRightData.value = [];
        return;
      }
      $api.group
        .groupReportTree(params)
        .then((res) => {
          pageLoading.value = false;
          dealTreeToList(res.data);
        })
        .catch((err) => {
          pageLoading.value = false;
          console.error("getPageData error: ", err);
        });
    };

    const dealTreeToList = (treeData) => {
      const viewData = [];
      let rightData = [];
      const fn = (list) => {
        if (list && Array.isArray(list)) {
          list.forEach((item) => {
            const newObj = cloneDeep(item);
            if (newObj.children) {
              delete newObj.children;
            }
            viewData.push(newObj);
            if (item.userReportCommitList && item.userReportCommitList.length) {
              rightData = rightData.concat(item.userReportCommitList);
            }
          });
          list.forEach((item) => {
            if (item.children) {
              fn(item.children);
            }
          });
        }
      };
      fn(treeData);
      // console.log("dealTreeToList ===> viewData", viewData);
      // console.log("dealTreeToList ===> rightData", rightData);
      pageData.value = viewData;
      rightData.forEach((item) => {
        item.sendLoadingCount = INIT_SEND_LOADING_COUNT;
        item.sendLoadingTimer = null;
      });
      pageRightData.value = rightData;
    };

    // 重置
    const handleReset = () => {
      filterData.createdTime = $moment().format("YYYY-MM-DD");
      resetOrgData();
      handleSearch();
    };

    const isShowReportEdit = ref(false);
    // 切换显示编辑日报
    const toggleEditReport = () => {
      isShowReportEdit.value = !isShowReportEdit.value;
    };

    // 重置机构绑定数据-初始值为当前登录人绑定的机构信息
    const resetOrgData = () => {
      // 此数据必须在 dom 挂载之后初始化，否则 v-model 绑定数据无法流向子组件
      orgInfo.value.orgId = userInfo.value.orgId;
      orgInfo.value.orgName = userInfo.value.orgName;
    };

    // 点击发送提醒（开启倒计时）
    const sendReportNotice = (item) => {
      if (item.sendLoadingTimer) return null;
      sendReportNoticeToUser(item.id);
      item.sendLoadingCount--;
      item.sendLoadingTimer = setInterval(() => {
        if (item.sendLoadingCount > 0) {
          item.sendLoadingCount--;
        } else {
          clearInterval(item.sendLoadingTimer);
          item.sendLoadingTimer = null;
          item.sendLoadingCount = INIT_SEND_LOADING_COUNT;
        }
      }, 1000);
    };

    const sendReportNoticeToUser = (userId) => {
      $api.message
        .sendReportNoticeToUser({
          userId,
        })
        .then((res) => {
          ElMessage.success("发送成功");
        })
        .catch((err) => {
          console.error("sendReportNoticeToUser error: ", err);
        });
    };

    // 初始化
    const initPageData = () => {
      resetOrgData();
      // 必须放在 resetOrgData 之后
      handleSearch();
    };

    /**
     * 初始化
     */
    onMounted(() => {
      initPageData();
    });

    onUnmounted(() => {
      // 回收定时器
      pageRightData.value.forEach((item) => {
        if (item.sendLoadingTimer) {
          clearInterval(item.sendLoadingTimer);
        }
      });
    });

    bus.on("TodayReportManageHandleSearch", handleSearch);
    onBeforeUnmount(() => {
      bus.off("TodayReportManageHandleSearch", handleSearch);
    });

    return {
      filterData,
      searchBtnLoading,
      userInfo,
      orgInfo,
      pageData,
      pageRightData,
      isShowReportEdit,
      INIT_SEND_LOADING_COUNT,
      handleSearch,
      handleReset,
      toggleEditReport,
      sendReportNotice,
    };
  },
};
</script>

<style lang="less" scoped>
.person_list {
  height: 100%;
  box-sizing: border-box;
  overflow: hidden auto;
  // padding: 10px 0;
  .person_content {
    width: 100%;
  }
  .cell_box {
    display: flex;
    border-bottom: 1px solid #fff;
  }
  .group_box {
    width: 20px;
    font-size: 16px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-evenly;
    word-break: break-all;
    letter-spacing: 0px;
    padding: 20px;
    line-height: 1.4;
    // background-image: linear-gradient(to right top, #ec008c, #6739b6);
    color: #fff;
    border-left: none;
    font-weight: 600;
  }
  .person_box {
    flex: 1;
    overflow: hidden;
  }
  .person_item {
    display: flex;
    align-items: center;
    padding: 10px 20px;
    cursor: pointer;
    &:hover {
      background-color: #f2f2f2;
    }
    .info_name {
      margin-left: 20px;
      flex: 1;
    }
  }
}

.clearfix {
  line-height: 28px;
}

.report_list {
  height: 100%;
  box-sizing: border-box;
  overflow: hidden auto;
}

.swiper_container {
  height: 100%;
  width: 100%;
  overflow: hidden;
  .swiper_content {
    height: 100%;
    display: flex;
    width: calc(100% * 2);
    transition: transform 0.3s ease-out;
    .swiper_slide {
      height: 100%;
      flex-shrink: 0;
      width: 50%;
    }
  }
}

.expand_wrapper {
  padding: 10px;
}

.report_cell_title {
  font-size: 16px;
  padding: 10px 20px;
  // background-image: linear-gradient(to right top, #ec008c, #6739b6);
  background-color: #faecd8;
  color: #303133;
  font-weight: 600;
  display: flex;
  align-items: center;
  justify-content: space-between;
  .time_text {
    font-size: 14px;
    font-weight: 400;
    color: #999;
  }
}

.arrow_icon {
  // font-size: 12px;
  color: #666;
  height: 12px;
  width: 12px;
}
</style>
